package interfaces;

import com.example.money.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


import databases.DsFavorecido;

public class FavorecidoAddActivity extends Activity {
	private String curNome;
	private Button btnCancela;
	private EditText campoLista;
	private DsFavorecido dbDataSource;
	private Bundle extras;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		curNome = "";
		
		extras = getIntent().getExtras();
		
		setContentView(R.layout.activity_favorecido_add);
		addListenerOnButton();
		
		campoLista = (EditText)findViewById(R.id.iptNome);
		
		if(extras != null)
		{
			curNome = extras.getString("nome");
			campoLista.setText(curNome);
		}
		
		dbDataSource = new DsFavorecido(this);
		dbDataSource.open();
	}

	public void addListenerOnButton(){
		btnCancela = (Button) findViewById(R.id.btnCancela);
		btnCancela.setOnClickListener(new OnClickListener() {
 			@Override
			public void onClick(View arg0) {
 				finish();
 				//startActivity(new Intent(FavorecidoAddActivity.this, FavorecidoActivity.class));
 	        }
 		});
		
		Button btnSalva = (Button) findViewById(R.id.btnSalvaAddFavorecido);
		btnSalva.setOnClickListener(new OnClickListener(){
			
			public void onClick(View v) {
				if(v.getId() == R.id.btnSalvaAddFavorecido)
				{
	 				String nome = campoLista.getText().toString();
	 				
	 				if(nome.length() == 0)
	 				{
	 					Toast.makeText(getApplicationContext(), R.string.nome_obrigatorio, Toast.LENGTH_LONG).show();
	 				}
	 				else
	 				{
	 					if(nome.equals(curNome))
	 					{
	 						finish();
	 					}
	 					else if(dbDataSource.hasName(nome))
						{
							Toast.makeText(getApplicationContext(), R.string.nome_usado, Toast.LENGTH_LONG).show();
						}
						else
						{
							if(extras == null)
							{
								if(dbDataSource.add(nome) == null)
								{
									Toast.makeText(getApplicationContext(), R.string.favorecido_salvar_erro, Toast.LENGTH_LONG).show();
								}
								else
								{
									Toast.makeText(getApplicationContext(), R.string.favorecido_salvar_sucesso, Toast.LENGTH_LONG).show();
									campoLista.setText("");
									
									finish();
								}
							}
							else
							{
								if(dbDataSource.rename(extras.getLong("id"), nome))
								{
									Toast.makeText(getApplicationContext(), R.string.categoria_renomear_sucesso, Toast.LENGTH_LONG).show();
									campoLista.setText("");
									
									finish();							
								}
								else
								{
									Toast.makeText(getApplicationContext(), R.string.categoria_renomear_erro, Toast.LENGTH_LONG).show();
								}
							}
						}
	 				}
				}
			}
		});
	}
}
